import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  Image,
  StyleSheet,
  Dimensions,
  Linking,
} from 'react-native';
import useHideTabBar from '../utils/useHideTabBar';
import theme from '../utils/theme';
import API, {getUserId} from '../Network/Api';
import { normalize, screenHeight } from "../utils/commonUtils";
import {showToast} from '../utils/toastUtils';
import Toast from 'react-native-toast-message';
import { CustomText } from "../customview/CustomText";

const TabBar = ({options, selected, onSelect}) => (
  <View style={styles.tabBar}>
    {options.map(option => (
      <TouchableOpacity
        key={option}
        style={[styles.tabItem, selected === option && styles.tabItemSelected]}
        onPress={() => onSelect(option)}>
        <CustomText
          style={[
            styles.tabItemText,
            selected === option && {color: theme.colors.primary},
          ]}>
          {option}
        </CustomText>
      </TouchableOpacity>
    ))}
  </View>
);

let isEnabled = true;

const WholesaleOrderPage = ({route, navigation}) => {
  const {initialRole, initialStatus, userPhone} = route.params; // 从路由参数中获取初始值·
  const [role, setRole] = useState(initialRole || '买方'); // 当前身份：买方或卖方
  const [status, setStatus] = useState(initialStatus || '买方仓库'); // 当前状态：仓库、交易中、已完成
  const [orders, setOrders] = useState([]); // 存储订单数据
  const [refreshing, setRefreshing] = useState(false); // 下拉刷新状态
  const [page, setPage] = useState(1); // 当前页码
  const [hasMore, setHasMore] = useState(false); // 是否还有更多数据
  useHideTabBar(navigation);

  useEffect(() => {
    fetchOrders(role, status, 1);
  }, [role, status]);

  // 根据角色选择不同的选项
  const statusOptions =
    role === '买方'
      ? ['买方仓库', '交易中', '已完成']
      : ['卖方仓库', '交易中', '已完成'];

  const handleRoleChange = newRole => {
    if (newRole === '卖方' && status === '买方仓库') {
      setStatus('卖方仓库');
    } else if (newRole === '买方' && status === '卖方仓库') {
      setStatus('买方仓库');
    }
    setRole(newRole);
  };

  const fetchOrders = async (role, status, currentPage) => {
    try {
      let response;
      const pageSize = '20';
      if (role === '买方') {
        if (status === '买方仓库') {
          response = await API.getBuyOrderInfoList(currentPage, pageSize);
        } else if (status === '交易中') {
          response = await API.getTransOrderInfoList(
            getUserId(),
            '',
            currentPage,
            pageSize,
          );
        } else if (status === '已完成') {
          response = await API.getCompletedOrderInfoList(
            getUserId(),
            '',
            currentPage,
            pageSize,
          );
        }
      } else {
        if (status === '卖方仓库') {
          response = await API.getSellOrderInfoList(currentPage, pageSize);
        } else if (status === '交易中') {
          response = await API.getTransOrderInfoList(
            '',
            getUserId(),
            currentPage,
            pageSize,
          );
        } else if (status === '已完成') {
          response = await API.getCompletedOrderInfoList(
            '',
            getUserId(),
            currentPage,
            pageSize,
          );
        }
      }

      if (response && response.resultCode === '1') {
        const newOrders =
          status === '卖方仓库'
            ? response.data.panicGoods.rows || []
            : response.data.orderInfo.rows || [];
        const total =
          status === '卖方仓库'
            ? response.data.panicGoods.total
            : response.data.orderInfo.total;
        if (currentPage === 1) {
          setOrders(newOrders);
        } else {
          setOrders(prevOrders => [...prevOrders, ...newOrders]);
        }
        setHasMore(orders.length + newOrders.length < total);
      } else {
        console.error(response ? response.showMsg : '未收到有效响应');
        setHasMore(false);
      }
    } catch (error) {
      console.error('获取订单数据失败:', error);
      setHasMore(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    setPage(1);
    await fetchOrders(role, status, 1);
    setRefreshing(false);
  };

  const onEndReached = async () => {
    if (hasMore) {
      const nextPage = page + 1;
      setPage(nextPage);
      await fetchOrders(role, status, nextPage);
    }
  };

  const priceText = (order, status) => {
    let price = order.spjg;
    // let price = status === '卖方仓库' ? order.spjg : order.zphjg;
    const priceFloat = parseFloat(price);
    const result = priceFloat.toFixed(2);
    const num = (result / theme.app.unitPrice).toFixed(0);
    return '商品价格：¥' + result + '  ≈ ' + num + '瓶';
  };

  const statueText = (spzt, role, status) => {
    if (role === '买方') {
      if (spzt === '4') {
        return '待支付';
      } else if (spzt === '5') {
        return '收款中';
      } else if (status === '已完成') {
        return '已完成';
      }
    } else if (role === '卖方') {
      if (spzt === '4') {
        return '付款中';
      } else if (spzt === '5') {
        return '待收款';
      } else if (spzt === '6') {
        return '提货中';
      } else if ((spzt === '3' || spzt === '9') && status !== '已完成') {
        return '寄卖中';
      } else if (status === '已完成') {
        return '买家已转拍';
      }
    }
  };

  const shouldShowButton = (order, role, status) => {
    if (role === '买方') {
      if (order.spzt === '4') {
        return (
          <TouchableOpacity
            style={styles.itemBtnStyle}
            onPress={() => updateGoodsStatus('5', order)}>
            <CustomText style={styles.itemBtnText}>立即支付</CustomText>
          </TouchableOpacity>
        );
      } else if (order.spzt === '6') {
        return (
          <TouchableOpacity
            style={styles.itemBtnStyle}
            onPress={() => updateGoodsStatus('7', order)}>
            <CustomText style={styles.itemBtnText}>立即提货</CustomText>
          </TouchableOpacity>
        );
      } else if (order.spzt === '7' && status !== '已完成') {
        return (
          <TouchableOpacity
            style={styles.itemBtnStyle}
            onPress={() => updateGoodsStatus('9', order)}>
            <CustomText style={styles.itemBtnText}>转拍</CustomText>
          </TouchableOpacity>
        );
      }
    } else if (role === '卖方') {
      if (order.spzt === '4') {
        return null;
      } else if (order.spzt === '5') {
        return (
          <TouchableOpacity
            style={styles.itemBtnStyle}
            onPress={() => updateGoodsStatus('7', order)}>
            <CustomText style={styles.itemBtnText}>确认收款</CustomText>
          </TouchableOpacity>
        );
      }
    }
  };

  const updateGoodsStatus = (spzt, order) => {
    if (isEnabled) {
      isEnabled = false;
      try {
        API.updateGoodsStatus(spzt, order.spid)
          .then(async response => {
            if (response.resultCode === '1') {
              await fetchOrders(role, status, 1);
            } else {
              if (response.data.errMsg.includes('服务费不足')) {
                showToast({text2: '服务费不足，请先充值！'});
              }
            }
          })
          .catch(error => {
            console.error('抢购失败:', error);
          });
      } catch (error) {
        console.error('转拍操作出错:', error);
      } finally {
        // 操作完成后，在一段时间后恢复按钮可点击状态
        setTimeout(() => {
          isEnabled = true;
        }, 300);
      }
    }
  };

  const callPhoneNumber = phoneNumber => {
    const url = `tel:${phoneNumber}`;
    Linking.canOpenURL(url)
      .then(supported => {
        if (!supported) {
          console.log('不支持拨打电话');
        } else {
          return Linking.openURL(url);
        }
      })
      .catch(err => console.error('拨打电话出错:', err));
  };

  const OrderItem = ({order, role, status}) => (
    <View style={styles.orderItem}>
      <View style={styles.orderHeader}>
        <CustomText style={styles.dateText}>时间：{order.updateTime}</CustomText>
        <CustomText style={styles.statusText}>
          {statueText(order.spzt, role, status)}
        </CustomText>
      </View>
      <View style={styles.separator} />
      <View style={styles.productInfo}>
        <Image source={theme.app.productImg} style={styles.productImage} />
        <View style={styles.productDetails}>
          <CustomText style={styles.productName}>{order.spbt}</CustomText>
          <CustomText style={styles.sessionName}>{order.qgcc}</CustomText>
          <CustomText style={styles.price}>{priceText(order, status)}</CustomText>
        </View>
      </View>
      <View style={[styles.separator, {marginHorizontal: 15}]} />
      {status === '卖方仓库' ? null : (
        <View style={styles.contactInfo}>
          <View style={styles.contactNameStyle}>
            <CustomText style={styles.contactNameText}>卖家：{order.sellName}</CustomText>
            <CustomText style={[styles.contactNameText, {marginTop: 10}]}>
              买家：{order.buyName}
            </CustomText>
          </View>
          <View style={styles.contactPhoneStyle}>
            <View style={{flexDirection: 'row'}}>
              <CustomText style={styles.contactPhoneText}>电话：</CustomText>
              <TouchableOpacity
                onPress={() => {
                  if (userPhone !== order.sellPhone) {
                    callPhoneNumber(order.sellPhone);
                  }
                }}>
                <CustomText
                  style={[
                    styles.contactPhoneText,
                    userPhone !== order.sellPhone
                      ? {color: theme.colors.info}
                      : {},
                  ]}>
                  {order.sellPhone}
                </CustomText>
              </TouchableOpacity>
            </View>
            <View style={{flexDirection: 'row', marginTop: 10}}>
              <CustomText style={styles.contactPhoneText}>电话：</CustomText>
              <TouchableOpacity
                onPress={() => {
                  if (userPhone !== order.buyPhone) {
                    callPhoneNumber(order.buyPhone);
                  }
                }}>
                <CustomText
                  style={[
                    styles.contactPhoneText,
                    userPhone !== order.buyPhone
                      ? {color: theme.colors.info}
                      : {},
                  ]}>
                  {order.buyPhone}
                </CustomText>
              </TouchableOpacity>
            </View>
          </View>
          {shouldShowButton(order, role, status)}
        </View>)}
    </View>
  );

  const EmptyListComponent = () => (
    <View style={styles.emptyListContainer}>
      <CustomText style={styles.emptyListText}>暂无订单数据</CustomText>
    </View>
  );

  return (
    <View style={styles.container}>
      {/* 顶部角色切换 */}
      <View style={styles.roleContainer}>
        <TabBar
          options={['买方', '卖方']}
          selected={role}
          onSelect={handleRoleChange}
        />
      </View>

      {/* 状态切换 */}
      <View style={styles.statusContainer}>
        <TabBar
          options={statusOptions}
          selected={status}
          onSelect={setStatus}
        />
      </View>

      {/* 订单列表 */}
      <FlatList
        data={orders}
        renderItem={({item}) => (
          <OrderItem order={item} role={role} status={status} />
        )}
        keyExtractor={item => item.id}
        onRefresh={onRefresh}
        refreshing={refreshing}
        onEndReached={onEndReached}
        onEndReachedThreshold={0.1}
        ListEmptyComponent={EmptyListComponent}
        showsVerticalScrollIndicator={false}
      />
      <Toast />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f8f8',
  },
  tabBar: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginVertical: 10,
    paddingHorizontal: 10,
  },
  tabItem: {
    paddingVertical: 5,
    alignItems: 'center',
    borderBottomWidth: 4,
    borderBottomColor: '#fff',
    marginHorizontal: 20,
    paddingBottom: 4,
  },
  tabItemSelected: {
    borderBottomColor: theme.colors.primary,
  },
  tabItemText: {
    fontSize: normalize(16),
    fontWeight: 600,
    color: '#666',
    lineHeight: 20,
  },
  roleContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: '#fff',
    height: 50,
  },
  statusContainer: {
    height: 50,
    justifyContent: 'center',
    backgroundColor: '#fff',
  },
  orderItem: {
    backgroundColor: '#ffffff',
    marginTop: 10,
    borderRadius: 10,
    marginHorizontal: 10,
  },
  orderHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginHorizontal: 10,
    marginVertical: 10,
  },
  dateText: {
    fontSize: normalize(14),
    color: '#333',
  },
  statusText: {
    fontSize: normalize(14),
    color: '#F96C0D',
  },
  separator: {
    height: 1,
    backgroundColor: '#979797',
    opacity: 0.2,
  },
  productInfo: {
    flexDirection: 'row',
  },
  productImage: {
    width: 65,
    height: 65,
    marginRight: 10,
    marginTop: 25,
    marginLeft: 15,
    marginBottom: 12,
  },
  productDetails: {
    flex: 1,
    marginTop: 25,
  },
  productName: {
    fontSize: normalize(16),
    fontWeight: 'bold',
    color: '#333',
  },
  sessionName: {
    fontSize: normalize(14),
    color: '#777',
    marginTop: 5,
  },
  price: {
    fontSize: normalize(14),
    color: '#F96C0D',
    marginTop: 5,
  },
  contactInfo: {
    flexDirection: 'row',
    marginLeft: 15,
    marginVertical: 10,
  },
  contactNameStyle: {
    backgroundColor: '#fff',
  },
  contactPhoneStyle: {
    backgroundColor: '#fff',
    marginLeft: 10,
  },
  contactNameText: {
    fontSize: normalize(14),
    color: '#555',
  },
  contactPhoneText: {
    fontSize: normalize(14),
    color: '#555',
  },
  itemBtnStyle: {
    position: 'absolute',
    right: 10,
    alignSelf: 'center',
    backgroundColor: theme.colors.primary,
    width: 65,
    height: 30,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 3,
  },
  itemBtnText: {
    color: '#fff',
  },
  emptyListContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: screenHeight / 3,
  },
  emptyListText: {
    flex: 1,
    fontSize: normalize(16),
    color: '#999',
  },
});

export default WholesaleOrderPage;
